package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.service.UserService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
//    @Resource
//    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login1")
    public ResponseBodyMessage<User> login1(@RequestParam String username,
                                           @RequestParam String password,
                                           HttpServletRequest request) {
        User userlogin = new User();
        userlogin.setUsername(username);
        userlogin.setPassword(password);

        User user = userService.login(userlogin);

        if (user != null) {
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(1, "登录成功", userlogin);
        } else {
            return new ResponseBodyMessage<>(-1, "登录失败", userlogin);
        }
    }

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username,
                      @RequestParam String password,
                    HttpServletRequest request) {


        User user = userService.selectByName(username);

        if (user != null) {
            boolean flg=bCryptPasswordEncoder.matches(password,user.getPassword());
                    if(!flg){
                        return new ResponseBodyMessage<>(-1, "登录失败", user);
                    }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(1, "登录成功", user);
        } else {
            System.out.println("登录失败！");
            return new ResponseBodyMessage<>(-1, "登录失败", user);
        }
    }
}
